import os
import wave
import json
import numpy as np
from flask import Blueprint, request, jsonify
from utilsapp.mysql_con import  db_table_pagelist,db_delete


bluePrint = Blueprint('wave', __name__)
tableName = 'wave'

@bluePrint.route('/getAll', methods=['POST'])
def getAll():
    name=request.json['name']
    file_names = []
    directory = os.path.dirname(os.path.abspath(__name__)) + '/static/audio/' + name
    if not os.path.exists(directory):
        return jsonify({'code': 0, 'msg': '该测点无音频波形', 'data': []}), 200
    for filename in os.listdir(directory):
        file_names.append(filename)
    return jsonify({'code': 0, 'msg': '获取成功', 'data': file_names}), 200

@bluePrint.route('/get', methods=['POST'])
def get():
    name=request.json['name']
    time=request.json['time']
    wav_file = wave.open(os.path.dirname(os.path.abspath(__name__)) + '/static/audio/' + name + '/' + time, 'rb')
    params = wav_file.getparams()
    audio_data = wav_file.readframes(params[3])
    audio_array = np.frombuffer(audio_data, dtype=np.int16)
    data,fregs = get_fft(audio_array,params[2])
    return jsonify({'code': 0, 'msg': '获取成功', 'data': data,'fregs': fregs,'audio_array' : audio_array.tolist(),'framerate': params[2]}),200 

def get_fft(data, fs):
    ll = len(data)
    fft_freqs = np.fft.fftfreq(ll, 1 / fs)
    fft_data = np.fft.fft(np.array(data) - np.mean(data))
    # 这里的y含有虚部
    fft_data_filter = fft_data[np.where(fft_freqs > 0)]
    fft_freqs_filter = fft_freqs[np.where(fft_freqs > 0)]
    return np.around(abs(fft_data_filter) / (ll / 2), 2).tolist(), np.around(fft_freqs_filter, 2).tolist()

@bluePrint.route('/upload', methods=["post"])
def upload():
    try:
        # 检查请求中是否包含文件
        if 'file' not in request.files:
            return jsonify({'code': -1, 'msg': '空文件'}), 200
        file = request.files['file']
        # 检查文件是否为空
        if file.filename == '':
            return jsonify({'code': -1, 'msg': '空文件'}), 200
        script_dir = os.path.dirname(os.path.abspath(__name__)) + '/static'
        split = file.filename.split("_")
        if len(split) == 5:
            split = [split[0] + '_' + split[1],split[2],split[3],split[4]]
        fileName = f'/audio/{split[0]}_{split[1]}'
        filePath = script_dir + fileName
        if not os.path.exists(script_dir + '/audio'):
            os.mkdir(script_dir + '/audio')
        if not os.path.exists(filePath):
            os.mkdir(filePath)
        file.filename = f'/{split[2]} {split[3]}'
        filePath = filePath + file.filename
        fileName = file.filename
        # 保存文件到指定目录
        file.save(filePath)
        return jsonify({'code': 0, 'msg': '上传成功', 'data': fileName}), 200
    except Exception as e:
        return jsonify({'code': -1, 'msg': '上传异常'}), 200